package com.haiyou.common.system;

import java.util.Map;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.haiyou.common.spring.component.LifecycleableComponent;
import com.haiyou.common.spring.util.SpringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @Description: spring Environment 配置参数
 * @author xingyuan
 * @date 2022年9月2日 下午4:23:31
 */
@Slf4j
@Component
public class SpringEnvironmentProperties extends ConfigProperties implements LifecycleableComponent {

	private boolean init = false;

	private Environment env;

	private Map<String, String> caches = Maps.newConcurrentMap();

	@Override
	public int getOrder() {
		return first_order;
	}

	@Override
	public void init() {
		try {
			env = SpringUtil.getBean(Environment.class);
			init = true;
		} catch (Exception e) {
			init = false;
			log.error(e.getMessage(), e);
		}
	}

	public void restCaches() {
		caches = Maps.newHashMap();
	}

	@Override
	public void destory() {

	}

	@Override
	public boolean initSuccess() {
		return init;
	}

	@Override
	public String getKey() {
		return Properties.spring;
	}

	@Override
	public String getString(String key, String defaultValue) {
		// 注意此处这么写,大部分情况下不需要创建lambda表达式
		String value = caches.getOrDefault(key, null);

		if (value == null) {
			return caches.computeIfAbsent(key, k -> {

				// log.info("缓存中没有 从环境参数读取 {}",key);

				// spring 环境中获取
				String value1 = env.getProperty(key);

				//log.info("从env 环境中读取{}:{}",key,value1);
				
				if (value1 == null) {
					// 从本地文件中获取
					value1 = ConfigProperties.getConfigProperties(Properties.file).getString(key, defaultValue);
				}

				return value1;
			});
		}

		return value;

	}

}
